﻿using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using PTop.Application.WeChat;
using PTop.Code;

namespace PTop.Front.Controllers
{
    public abstract class PTopControllerBase : Controller
    {
        private string _openId;

        public string OpenId
        {
            get
            {
                //if (IsLocalRequest()) return "oXoTIvqUm2I1Bpoo9qlIKFSyceM0";
                if (!string.IsNullOrEmpty(_openId)) return _openId;
                _openId = Request.Cookies["wxopenid"] != null ? Request.Cookies["wxopenid"].Value : "";
                //FileLog.Info("_openId:" + _openId + "\r\n");
                return _openId;
            }
        }
        [HttpGet]
        public virtual ActionResult Index()
        {
            SetOpenIdCookie();
            return View();
        }
        /// <summary>
        /// 将微信OpenId存到Cookie
        /// </summary>
        public void SetOpenIdCookie()
        {
            //if (IsLocalRequest()) return;

            //订阅号没有网页授权，不能铜鼓哦outh获取用户信息
            if (Request.Cookies.Get("wxopenid") == null)
            {
                _openId = Guid.NewGuid().ToString("N");
                var cookie = new HttpCookie("wxopenid", _openId) { Expires = DateTime.Now.AddYears(1), Domain = ".smartyunfeng.top" };
                Response.Cookies.Add(cookie);
                return;
            }
            else
            {
                _openId = Request.Cookies.Get("wxopenid").Value;
                if (_openId == "System.Web.HttpCookie")
                {
                    _openId = Guid.NewGuid().ToString("N");
                }
                var cookie = new HttpCookie("wxopenid", _openId) { Expires = DateTime.Now.AddYears(1), Domain = ".smartyunfeng.top" };
                Response.Cookies.Add(cookie);
                return;
            }

            var code = Request["code"];
            //如果不是微信回调，并且OpenId未写入cookie，则通过微信oauth2回调
            if (string.IsNullOrEmpty(code) && string.IsNullOrEmpty(OpenId))
            {
                var fromUrl = Request.Url.ToString();
                if (!fromUrl.Contains("#/"))
                {
                    fromUrl = fromUrl + "#/";
                }
                fromUrl = fromUrl.Replace(":" + Configs.GetValue("OrayPort"), "");//针对花生壳内网穿透
                var wxOauthUrl = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect", Configs.GetValue("WeChatAppId"), HttpUtility.UrlEncode(fromUrl, Encoding.UTF8));
                Response.Redirect(wxOauthUrl);
                Response.End();
            }
            if (!string.IsNullOrEmpty(code))
            {
                //如果微信oauth2回调，则获取openid并写入cookie
                _openId = new WxApiApp().GetWeChatOpenId(code);
                var cookie = new HttpCookie("wxopenid", _openId) { Expires = DateTime.Now.AddDays(30) };
                Response.Cookies.Add(cookie);
            }
        }
        /// <summary>
        /// 本地测试访问
        /// </summary>
        /// <returns></returns>
        public bool IsLocalRequest()
        {
            return Request.Url.Host == "local.bus.com";
        }
        public Log FileLog
        {
            get { return LogFactory.GetLogger(this.GetType().ToString()); }
        }
        protected virtual ActionResult Success(string message)
        {
            return Content(new AjaxResult { state = ResultType.success.ToString(), message = message }.ToJson());
        }
        protected virtual ActionResult Success(string message, object data)
        {
            return Content(new AjaxResult { state = ResultType.success.ToString(), message = message, data = data }.ToJson());
        }
        protected virtual ActionResult Error(string message)
        {
            return Content(new AjaxResult { state = ResultType.error.ToString(), message = message }.ToJson());
        }
    }
}
